import { createStore } from 'vuex'

const store = createStore({
	state: {
		token: '',
		userInfo: uni.getStorageSync('userInfo') || {},
		roles: [],
		currentRole: "",
		cartList: [], //购物车列表
		orderInfo: {}, //商品信息
		orderAddress: {},
		goodsDetails:{},
		couponId: "",//优惠券id
	},
	mutations: {
		SET_DATA: (state, {
			key,
			value
		}) => {
			state[key] = value
		},
		SET_USERINFO: (state, data) => {
			state.userInfo = data
		},
	},
	actions: {
		//获取用户信息
		getUserInfo({
			commit,
			dispatch
		}) {
			return new Promise((resolve, reject) => {
				api.getUserInfo().then(res => {
					uni.setStorageSync('userInfo', res)
					commit('SET_USERINFO', res)
					resolve()
				}).catch(err => {
					reject(err)
				})
			})
		},
		// 用户名登录
		login({
			commit,
			dispatch
		}) {
			return new Promise((resolve, reject) => {
				uni.getUserProfile({
					desc: '用以获取用户昵称、头像等',
					success({
						encryptedData,
						iv,
						rawData,
						signature
					}) {
						uni.login({
							provider: 'weixin',
							success({
								code
							}) {
								const params = {
									encryptedData,
									iv,
									rawData,
									signature,
									code,
								}
								api.login(params).then(res => {
									uni.setStorageSync('token', res
										.access_token)
									dispatch("getUserInfo")
									resolve()
								}).catch(error => {
									reject(error)
								})
							}
						});
					},
					fail(err) {
						reject(err)
					}
				})
			})
		},
		// 用户退出
		lotOut({
			commit
		}) {
			uni.removeStorage('token')
			uni.removeStorage('userInfo')
			uni.navigateTo({
				url: '/pages/index/index'
			})
		},
		// 获取购物车列表
		getCartList({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getCartList().then(res => {
					const data = res.list
					if (data) {
						data.map(item => {
							if(!item.goods_list.length)return
							item.goods_list.map(child => {
								child.checked = false
							})
						})
					}
					commit('SET_CARTLIST', data || [])
					resolve()
				})
			})
		},
		// 加入购物车
		addCart({
			commit,
			dispatch
		}, data) {
			return new Promise((resolve, reject) => {
				console.log(data)
				addCart(data).then(() => {
					uni.showToast({
						icon: 'success',
						title: "已加入购物车",
						duration: 2000
					})
					dispatch('getCartList')
					resolve()

				}).catch(err => {
					reject(err)
				})
			})
		},
	},
	getters: {
		userInfo: (state) => {
			return state.userInfo
		}
	}
})
export default store
